#ifndef A8_COMPAT_H
#define A8_COMPAT_H

#include <assert.h>

typedef union uEndianTest{
    struct
    {
        bool flittle_endian;
        bool fill[3];
    };
    long value;
}EndianTest;
static const EndianTest __Endian_Test__ = { (long)1 };
const bool platform_little_endian = __Endian_Test__.flittle_endian;

static inline int convertToLittleEndian(int n)
{
    return	(  (n & 0xff000000) >> 24)
        | ((n & 0x00ff0000) >>  8)
        | ((n & 0x0000ff00) <<  8)
        | ((n & 0x000000ff) << 24);
}

static inline unsigned int convertToLittleEndian(unsigned int n)
{
    return	(  (n & 0xff000000) >> 24)
        | ((n & 0x00ff0000) >>  8)
        | ((n & 0x0000ff00) <<  8)
        | ((n & 0x000000ff) << 24);
}

static inline short convertToLittleEndian(short n)
{
    return	(  (n & 0xff00) >> 8)
        | ((n & 0x00ff) << 8);
}

static inline unsigned short convertToLittleEndian(unsigned short n)
{
    return	(  (n & 0xff00) >> 8)
        | ((n & 0x00ff) << 8);
}

static inline int convertToBigEndian(int n)
{
    return	(  (n & 0x000000ff) << 24)
        | ((n & 0x0000ff00) <<  8)
        | ((n & 0x00ff0000) >>  8)
        | ((n & 0xff000000) >> 24);
}

static inline unsigned int convertToBigEndian(unsigned int n)
{
	return	(  (n & 0x000000ff) << 24)
        | ((n & 0x0000ff00) <<  8)
        | ((n & 0x00ff0000) >>  8)
        | ((n & 0xff000000) >> 24);
}

static inline short convertToBigEndian(short n)
{
    return	(  (n & 0x00ff) << 8)
        | ((n & 0xff00) >> 8);
}

static inline unsigned short convertToBigEndian(unsigned short n)
{
    return	(  (n & 0x00ff) << 8)
        | ((n & 0xff00) >> 8);
}

#pragma warning(push)
#pragma warning(disable: 4146) 
template <typename Type>
static int XItoa(Type n, char* buf, int bufLen, int radix)
{
    if(!buf){
		return 0;
	}

    int isNeg = 0;
    if(n < 0){
        isNeg = 1;
        n = -n;
    }
    char* p = buf;
  
    do{
		*p++ = "0123456789ABCDEF"[n % radix];
        n /= radix;
    }while(n);
    if(isNeg){
		buf[p - buf] = '-';
		buf[p - buf + 1] = 0;
	}else{
		buf[p - buf] = 0;
	}

    int i, j;
    for(i = 0, j = strlen(buf) - 1; i < j; i++, j--){
        buf[j] = buf[i] + buf[j];
        buf[i] = buf[j] - buf[i];
        buf[j] = buf[j] - buf[i];
    }

    return 1;
}
#pragma warning( pop )

static std::string ws2s(const std::wstring& ws)
{
#ifdef WIN32
	//require comutil.h
    _bstr_t t = ws.c_str();
    char* pchar = (char*)t;
    std::string result = pchar;
    return result;
#else
	assert(false);
#endif
}

static std::wstring s2ws(const std::string& s)
{
#ifdef WIN32
	//require comutil.h
	_bstr_t t = s.c_str();
	wchar_t* pwchar = (wchar_t*)t;
	std::wstring result = pwchar;
	return result;
#else
	assert(false);
#endif
}

#endif
